<?php

if($uri == "/api/admin/upload"){
    // 记录请求信息
    error_log("Received upload request: " . print_r($_FILES, true));
    
    // 检查是否有文件上传
    if (!isset($_FILES['image'])) {
        error_log("No file uploaded. Available fields: " . print_r(array_keys($_FILES), true));
        echo json_encode(['code'=>400, 'msg'=>'没有上传文件']);
        exit;
    }

    $file = $_FILES['image'];
    error_log("File info: " . print_r($file, true));
    
    // 检查上传是否成功
    if ($file['error'] !== UPLOAD_ERR_OK) {
        error_log("Upload error: " . $file['error']);
        echo json_encode(['code'=>400, 'msg'=>'文件上传失败: ' . $file['error']]);
        exit;
    }

    // 检查文件类型
    $allowed = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowed)) {
        error_log("Invalid file type: " . $file['type']);
        echo json_encode(['code'=>400, 'msg'=>'只允许上传jpg/png/gif图片']);
        exit;
    }

    // 检查文件大小
    if ($file['size'] <= 0) {
        error_log("File size is zero or invalid");
        echo json_encode(['code'=>400, 'msg'=>'文件内容无效']);
        exit;
    }

    // 检查临时文件是否存在
    if (!file_exists($file['tmp_name'])) {
        error_log("Temporary file does not exist: " . $file['tmp_name']);
        echo json_encode(['code'=>500, 'msg'=>'临时文件不存在']);
        exit;
    }

    // 生成随机文件名
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid() . '.' . $ext;
    
    // 确保上传目录存在并有正确的权限
    $upload_dir = __DIR__ . '/../../uploads/';
    if (!file_exists($upload_dir)) {
        if (!mkdir($upload_dir, 0777, true)) {
            error_log("Failed to create upload directory: " . $upload_dir);
            echo json_encode(['code'=>500, 'msg'=>'创建上传目录失败']);
            exit;
        }
        chmod($upload_dir, 0777);  // 确保目录有写入权限
    }

    // 检查目录是否可写
    if (!is_writable($upload_dir)) {
        error_log("Upload directory is not writable: " . $upload_dir);
        echo json_encode(['code'=>500, 'msg'=>'上传目录无写入权限']);
        exit;
    }

    // 移动文件到目标位置
    $filepath = $upload_dir . $filename;
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        $error = error_get_last();
        error_log("Failed to move uploaded file. Error: " . print_r($error, true));
        error_log("From: " . $file['tmp_name'] . " To: " . $filepath);
        
        // 尝试直接复制
        if (!copy($file['tmp_name'], $filepath)) {
            error_log("Failed to copy file as fallback");
            echo json_encode(['code'=>500, 'msg'=>'文件保存失败']);
            exit;
        }
    }

    // 确保文件权限正确
    chmod($filepath, 0644);

    // 返回文件访问路径
    $url = '/uploads/' . $filename;
    error_log("Upload successful. URL: " . $url);
    echo json_encode([
        'code' => 200,
        'msg' => '上传成功',
        'data' => [
            'url' => $url
        ]
    ]);
}